package cn.wolfcode.edu.web.controller;

import cn.wolfcode.edu.domain.Employee;
import cn.wolfcode.edu.domain.Salary;
import cn.wolfcode.edu.query.SalaryQueryObject;
import cn.wolfcode.edu.service.ISalaryService;
import cn.wolfcode.edu.util.JsonResult;
import cn.wolfcode.edu.util.PageResult;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
@RequestMapping("salary")
public class SalaryController {
    @Autowired
    private ISalaryService salaryService;

    //导航页面方法
    @RequestMapping("")
    public String index() {
        return "salary";
    }

    //查询数据方法
    @ResponseBody
    @RequestMapping("list")
    public PageResult list(SalaryQueryObject qo) {
        return salaryService.list(qo);
    }

    //删除数据方法
    @ResponseBody
    @RequestMapping("delete")
    public JsonResult delete(Long id) {
        JsonResult jsonResult = new JsonResult();
        try {
            salaryService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.remark("删除失败");
        }
        return jsonResult;
    }

    @ResponseBody
    @RequestMapping("update")
    public JsonResult update(Salary salary) {
        JsonResult jsonResult = new JsonResult();
        try {
            salaryService.update(salary);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.remark("更新失败");
        }
        return jsonResult;
    }

    //核算方法
    @ResponseBody
    @RequestMapping("account")
    public JsonResult account(Long id) {
        JsonResult jsonResult = new JsonResult();
        try {
            salaryService.account(id);
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.remark("核算失败");
        }
        return jsonResult;
    }

    //文件导出方法
    @RequestMapping("export")
    @ResponseBody
    public void export(SalaryQueryObject qo, HttpServletResponse resp) throws Exception {
        qo.setRows(2000);
        java.util.List list = salaryService.queryForList(qo);
        SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM-dd");
        resp.setHeader("Content-Disposition", "attachment;filename=salary.xls");
        ServletOutputStream outputStream = resp.getOutputStream();
        //创建一个工作簿
        WritableWorkbook workbook = Workbook.createWorkbook(outputStream);
        //创建sheet
        WritableSheet sheet = workbook.createSheet("salary", 0);
        Label empId = new Label(0, 0, "员工编号");
        Label realName = new Label(1, 0, "姓名");
        Label month = new Label(2, 0, "月份");
        Label salary = new Label(3, 0, "基本工资");
        Label workDays = new Label(4, 0, "工作天数");
        Label lateDays = new Label(5, 0, "迟到天数");
        Label earlyDays = new Label(6, 0, "早退天数");
        Label finalSalary = new Label(7, 0, "总工资");
        Label stockDater = new Label(8, 0, "结算时间");
        sheet.addCell(empId);
        sheet.addCell(realName);
        sheet.addCell(month);
        sheet.addCell(salary);
        sheet.addCell(workDays);
        sheet.addCell(lateDays);
        sheet.addCell(earlyDays);
        sheet.addCell(finalSalary);
        sheet.addCell(stockDater);
        for (int i = 0; i < list.size(); i++) {
            Salary e = (Salary) list.get(i);
            int row = i + 1;
            Label id = new Label(0, row, e.getEmployee().getId().toString());
            Label realNameCon = new Label(1, row, e.getEmployee().getRealName());
            Label monthCon = new Label(2, row, sdfMonth.format(e.getMonth()).toString());
            Label salaryCon = new Label(3, row, e.getSalary().toString());
            Label workDaysCon = new Label(4, row, e.getWorkDays().toString());
            Label lateDaysCon = new Label(5, row, e.getLateDays().toString());
            Label earlyDaysCon = new Label(6, row, e.getEarlyDays().toString());
            BigDecimal finalSalary1 = e.getFinalSalary();
            Label finalSalaryCon = new Label(7, row, finalSalary1 == null ? "" : finalSalary1.toString());
            Date stockDater1 = e.getStockDater();
            Label stockDaterCon = new Label(8, row, stockDater1 == null ? "未結算" : stockDater1.toLocaleString());
            sheet.addCell(id);
            sheet.addCell(realNameCon);
            sheet.addCell(monthCon);
            sheet.addCell(salaryCon);
            sheet.addCell(workDaysCon);
            sheet.addCell(lateDaysCon);
            sheet.addCell(earlyDaysCon);
            sheet.addCell(finalSalaryCon);
            sheet.addCell(stockDaterCon);
        }
        workbook.write();
        workbook.close();
    }

    @RequestMapping("download")
    @ResponseBody
    public void download(HttpServletResponse response, Long id, HttpSession session) throws Exception {
        Salary salary = salaryService.selectByPrimaryKey(id);
        session.setAttribute("PAYROLL_IN_SESSION", salary);
        String fileName = new String("工资表模板".getBytes("utf-8"), "ISO-8859-1");
        response.setHeader("Content-Disposition", (new StringBuilder()).
                append("attachment;filename=").append(fileName).append(".xls").toString());
        WritableWorkbook workBook = Workbook.createWorkbook(response.getOutputStream());
        WritableSheet sheet = workBook.createSheet("工资表模板", 0);

        sheet.addCell(new Label(0, 0, "员工编号"));
        sheet.addCell(new Label(1, 0, "员工姓名"));
        sheet.addCell(new Label(2, 0, "月份"));
        sheet.addCell(new Label(3, 0, "基本工资"));
        sheet.addCell(new Label(4, 0, "工作天数"));
        sheet.addCell(new Label(5, 0, "迟到天数"));
        sheet.addCell(new Label(6, 0, "早退天数"));
        sheet.addCell(new Label(7, 0, "总工资"));
        sheet.addCell(new Label(8, 0, "结算时间"));
        workBook.write();
        workBook.close();
    }

    @RequestMapping("importXls")
    @ResponseBody
    public JsonResult importXls(MultipartFile file) {
        JsonResult jsonResult = new JsonResult();
        try {
            Workbook workBook = null;
            workBook = Workbook.getWorkbook(file.getInputStream());
            Sheet sheet = workBook.getSheet(0);
            int rows = sheet.getRows();
            //设置时间的格式
            SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfPayTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i = 1; i < rows; i++) {
                Employee employee = new Employee();

                Salary salary = new Salary();
                String contents = sheet.getCell(0, i).getContents();
                employee.setId(Long.valueOf(contents));
                salary.setEmployee(employee);

                contents = sheet.getCell(1, i).getContents();
                employee.setRealName(contents);
                salary.setEmployee(employee);

                contents = sheet.getCell(2, i).getContents();
                salary.setMonth(sdfMonth.parse(contents));

                contents = sheet.getCell(3, i).getContents();
                salary.setSalary(new BigDecimal(contents));

                contents = sheet.getCell(4, i).getContents();
                salary.setWorkDays(Integer.valueOf(contents));

                contents = sheet.getCell(5, i).getContents();
                salary.setLateDays(Integer.valueOf(contents));

                contents = sheet.getCell(6, i).getContents();
                salary.setEarlyDays(Integer.valueOf(contents));

                contents = sheet.getCell(7, i).getContents();
                if(!"".equals(contents)){
                salary.setFinalSalary(new BigDecimal(contents));
                }
                contents = sheet.getCell(8, i).getContents();
                if(!"未結算".equals(contents)){
                salary.setStockDater(sdfPayTime.parse(contents));
                }
                salaryService.insertFromFile(salary);
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.remark("导入失败!");
        }
        return jsonResult;
    }

}
